package controller

import (
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"log"
	"websocket/commom"
	"websocket/dto"
	"websocket/model"
	"websocket/response"
	"websocket/util"
)

//注册
func Register(c *gin.Context) {
	json := model.User{}
	c.BindJSON(&json)
	db := commom.GetDB()
	//获取参数
	username := json.UserName
	password := json.Password
	tel := json.Tel
	//数据验证
	if len(tel) != 11 {
		if len(tel) == 0 {
			response.FailWithMessage("手机号不能为空", c)
			return
		}
		response.FailWithMessage("手机不足11位数", c)
		return
	}
	if len(tel) == 0 {
		response.FailWithMessage("手机号不存在", c)
		return
	}
	if len(password) < 6 {
		response.FailWithMessage("密码不能小于六位数", c)
		return
	}
	//判断手机是否存在
	if model.IsTelExist(db, tel) {
		response.FailWithMessage("手机号已经被注册", c)
		return
	}
	//如果没有名次，自动生成10位数的名次
	if username == "" {
		username = util.RandomString(10)
	}
	//创建用户

	//md5加密1
	hasedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	//md5加密2
	//hesedPasswrod :=util.MD5V([]byte(password))
	if err != nil {
		response.FailWithServerError("加密失败", c)
		log.Printf("md5 generate error : %v", err)
		return
	}
	newUser := model.User{
		UserName: username,
		Tel:      tel,
		Password: string(hasedPassword),
	}
	err = db.Table("user").Create(&newUser).Error
	if err != nil {
		response.FailWithServerError("注册失败", c)
		log.Printf("md5 generate error : %v", err)
		return
	}
	//返回结果
	c.JSON(200, gin.H{
		"message": "注册成功",
	})
}

//登录
func Login(c *gin.Context) {
	json := model.User{}
	c.BindJSON(&json)
	db := commom.GetDB()
	//获取参数
	tel := json.Tel
	password := json.Password
	//数据验证
	if len(tel) != 11 {
		response.FailWithMessage("手机号不能为空", c)
		return
	}

	if len(tel) == 0 {
		response.FailWithMessage("手机号不存在", c)
		return
	}
	if len(password) < 6 {
		response.FailWithMessage("密码不能小于六位数", c)
		return
	}
	//判断手机号是否存在
	user := model.GetUser(db, tel)
	if user.Id == 0 {
		response.FailWithMessage("手机号不存在", c)
		return
	}
	//判断密码是否正确
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		response.FailWithMessage("密码错误", c)
		return
	}
	//发放token
	token, err := util.ReleaseToken(user)
	if err != nil {
		response.FailWithServerError("token失败", c)
		log.Printf("token generate error : %v", err)
		return
	}
	//更新token
	model.Update(db, tel, token, 1)
	//返回结果
	response.OkWithData(gin.H{"token": token}, c)
}

//详情
func Info(c *gin.Context) {
	user, _ := c.Get("user")
	response.OkWithData(dto.ToUserDto(user.(model.User)), c)

}
